<template>
  <div class="schedule-page">
    <!-- 顶部信息 -->
    <div class="header">
      <!-- <h2>排产</h2> -->
      <div class="info">
        工单号：{{ info.docNo }}　 品号：{{ info.itemCode }}　 车间：{{
          info.workshopName
        }}　 产线：{{ info.lineName }}　 产线排产数量：{{ info.planQty }}
      </div>
      <div class="actions">
        <!-- <el-link @click="viewDetail">查看排程</el-link> -->
        <!-- <el-button @click="goBack" size="mini">返回</el-button> -->
      </div>
    </div>

    <div class="calendar-container">
      <!-- 页面标题区域 -->
      <div class="page-header">
        <div class="title-bar">
          <div class="info-bar">
            <span class="info-text">已排数量：{{ info.alreadyQty }}</span>
            <span class="info-text">待排数量：{{ info.waitQty }}</span>
            <a href="javascript:;" class="detail-link" @click="getDetail"
              >查看详情</a
            >
          </div>
          <h2>{{ year }} 年 {{ month }} 月</h2>
          <div class="month-nav">
            <button class="month-btn" @click="preMonth">上个月</button>
            <button class="month-btn active" @click="nowMonth">当月</button>
            <button class="month-btn" @click="nextMonth">下个月</button>
          </div>
        </div>
      </div>

      <!-- 表格主体区域 -->
      <div class="calendar-table">
        <!-- 表头 -->
        <div class="table-header">
          <div class="table-cell">周一</div>
          <div class="table-cell">周二</div>
          <div class="table-cell">周三</div>
          <div class="table-cell">周四</div>
          <div class="table-cell">周五</div>
          <div class="table-cell">周六</div>
          <div class="table-cell">周日</div>
        </div>

        <!-- 表格内容 -->
        <div class="table-body">
          <div
            class="table-row"
            v-for="(row, rowIndex) in getRowCount()"
            :key="rowIndex"
          >
            <div
              class="table-cell"
              v-for="(col, colIndex) in 7"
              :key="colIndex"
            >
              <div v-if="getCurrentCell(rowIndex * 7 + colIndex)">
                <div class="date-number">
                  {{ getCurrentCell(rowIndex * 7 + colIndex).day }}
                </div>
                <div
                  class="date-info"
                  v-if="getCurrentCell(rowIndex * 7 + colIndex).day"
                >
                  <div class="prod-total">
                    产线总排：<el-link
                      @click="
                        viewDetail(getCurrentCell(rowIndex * 7 + colIndex))
                      "
                      ><span style="color: #3782f4">{{
                        getCurrentCell(rowIndex * 7 + colIndex).lineCount
                      }}</span>
                    </el-link>
                  </div>
                  <div
                    class="work-order"
                    style="
                      display: flex;
                      align-items: center;
                      align-items: center;
                    "
                  >
                    工单已排：<span
                      v-if="!getCurrentCell(rowIndex * 7 + colIndex).isEditing"
                      style="
                        display: inline-block;
                        display: flex;
                        justify-content: space-between;
                        width: 70%;
                        align-items: center;
                      "
                    >
                      {{ getCurrentCell(rowIndex * 7 + colIndex).planQty }}
                      <a
                        v-if="getCurrentCell(rowIndex * 7 + colIndex).isAbled"
                        href="javascript:;"
                        class="edit-link"
                        @click="
                          getCurrentCell(
                            rowIndex * 7 + colIndex
                          ).isEditing = true
                        "
                        >✏️</a
                      >
                    </span>
                    <div v-else>
                      <input
                        type="number"
                        v-model="
                          getCurrentCell(rowIndex * 7 + colIndex).planQty
                        "
                        @blur="saveEdit(rowIndex * 7 + colIndex)"
                        @keyup.enter="saveEdit(rowIndex * 7 + planQty)"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 当日已排 -->
    <el-dialog
      :title="`当日已排(${year}年${month}月${selectDay}日)`"
      :visible.sync="dialogVisibleDay"
      append-to-body
      width="50%"
    >
      <div>
        <productionSchedulingDay
          :scheduleTime="scheduleTime"
          :lineId="lineId"
          :dialogVisibleDay="dialogVisibleDay"
        ></productionSchedulingDay>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleDay = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisibleDay = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 排产详情 -->
    <el-dialog
      title="查看详情"
      :visible.sync="dialogVisibleDetail"
      append-to-body
      width="50%"
    >
      <div>
        <productionSchedulingDetail
          :scheduleTime="scheduleTimeVal"
          :lineId="lineId"
          :docNo="docNo"
          :dialogVisibleDetail="dialogVisibleDetail"
        ></productionSchedulingDetail>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleDetail = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisibleDetail = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import {
  getProductionScheduling,
  saveProductionScheduling,
} from "@/api/workorder/productionscheduling";
import productionSchedulingDay from "./productionSchedulingDay.vue";
import productionSchedulingDetail from "./productionSchedulingDetail.vue";
export default {
  data() {
    return {
      info: {
        docNo: "",
        itemCode: "",
        workshopName: "",
        lineName: "",
        planQty: 0,
        alreadyQty: 0,
        waitQty: 0,
      },
      month: new Date().getMonth() + 1,
      year: new Date().getFullYear(),
      selectDay: "",
      calendarDataCopy: [],
      calendarData: [],
      mainId: "",
      lineId: "",
      docNo: "",
      dialogVisibleDay: false,
      dialogVisibleDetail: false,
      scheduleTime: "",
    };
  },
  computed: {
    scheduleTimeVal() {
      return `${this.year}-${this.month > 9 ? this.month : "0" + this.month}`;
    },
  },

  props: {
    orderId: {
      type: String,
    },
    planDialogVisible: {
      type: Boolean,
    },
  },
  components: {
    productionSchedulingDay,
    productionSchedulingDetail,
  },

  watch: {
    planDialogVisible: {
      handler(val) {
        if (val) {
          this.month = new Date().getMonth() + 1;
          this.year = new Date().getFullYear();
          this.getProductionPlanData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    getDetail() {
      this.dialogVisibleDetail = true;
    },
    nowMonth() {
      this.month = new Date().getMonth() + 1;
      this.year = new Date().getFullYear();
      this.getProductionPlanData();
    },
    preMonth() {
      this.month--;
      if (this.month < 1) {
        this.month = 12;
        this.year--;
      }

      this.getProductionPlanData();
    },
    nextMonth() {
      this.month++;
      if (this.month > 12) {
        this.month = 1;
        this.year++;
      }
      this.getProductionPlanData();
    },
    getFirstDayOfWeek(year, month) {
      // 创建一个 Date 对象，表示指定年份和月份的 1 号
      // 注意：月份是从 0 开始计数的，0 表示 1 月，11 表示 12 月
      var firstDay = new Date(year, month, 1);

      // getDay() 方法返回星期几，0 表示星期日，1 表示星期一，以此类推
      var dayOfWeek = firstDay.getDay();

      // 如果 1 号是星期日，返回 7
      if (dayOfWeek === 0) {
        return 7;
      } else {
        return dayOfWeek;
      }
    },

    getProductionPlanData() {
      const nullnum = this.getFirstDayOfWeek(this.year, this.month - 1);

      console.log(111, this.year, this.month, nullnum);

      getProductionScheduling(
        this.orderId,
        `${this.year}-${this.month > 9 ? this.month : "0" + this.month}`
      ).then((res) => {
        console.log("查询结果：", res.data.data);

        this.info.docNo = res.data.data.docNo;
        this.info.itemCode = res.data.data.itemCode;
        this.info.workshopName = res.data.data.workshopName;
        this.info.lineName = res.data.data.lineName;
        this.info.planQty = res.data.data.planQty;
        this.info.alreadyQty = res.data.data.alreadyQty;
        this.info.waitQty = res.data.data.waitQty;
        this.mainId = res.data.data.mainId;
        this.lineId = res.data.data.lineId;
        this.docNo = res.data.data.docNo;

        let nList = res.data.data.scheduleDetailsList.map((item) => {
          return {
            ...item,
            isEditing: false,
            isAbled: this.isBeforeToday(item.scheduleTime),
          };
        });

        console.log("nList:", nList);

        this.calendarData = this.addEmptyObjectsToFront(nList, nullnum - 1);
      });
    },

    isBeforeToday(dateString) {
      // 解析输入日期
      const inputDate = new Date(dateString);
      // 处理当天的日期（去掉时间部分）
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      // 比较日期
      return inputDate > today;
    },
    addEmptyObjectsToFront(arr, count) {
      // 创建一个包含 count 个空对象的新数组
      const emptyObjects = Array.from({ length: count }, () => ({}));

      // 将空对象添加到原数组的前面
      emptyObjects.forEach((obj) => {
        arr.unshift(obj);
      });

      return arr;
    },

    viewDetail(row) {
      console.log("查看详情：", row);
      this.scheduleTime = row.scheduleTime;
      this.selectDay = row.day;

      this.dialogVisibleDay = true;
    },
    goBack() {
      this.$message("返回");
    },

    getCurrentCell(index) {
      if (index < this.calendarData.length) {
        return this.calendarData[index];
      }
      return null;
    },
    getRowCount() {
      return Math.ceil(this.calendarData.length / 7);
    },
    saveEdit(index) {
      this.getCurrentCell(index).isEditing = false;

      let data = {
        mainId: this.mainId,
        scheduleTime: this.calendarData[index].scheduleTime,
        day: this.calendarData[index].day,
        planQty: this.calendarData[index].planQty,
      };

      saveProductionScheduling(data).then((res) => {
        console.log("编辑结果：", res);
        if (res) {
          this.$message.success("编辑成功");
        }
      });

      setTimeout(() => {
        this.getProductionPlanData();
      }, 1000);
    },
  },
};
</script>

<style scoped>
.schedule-page {
  background: #fff;
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.info {
  font-size: 14px;
  margin-bottom: 10px;
}
.actions {
  float: right;
}
.summary {
  margin: 10px 0;
}
.calendar-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.calendar-title {
  margin-left: 20px;
  font-weight: bold;
}
.calendar-cell {
  min-height: 80px;
  border-bottom: 1px solid #eee;
  padding: 5px;
}
.date-label {
  font-weight: bold;
}
.calendar-container {
  width: 100%;
  font-family: Arial, sans-serif;
  margin-top: 20px;
}

.page-header {
  display: flex;
  flex-direction: column;
  margin-bottom: 15px;
}

.info-bar {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.info-text {
  margin-right: 20px;
}

.detail-link {
  color: #2196f3;
  cursor: pointer;
}

.title-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.month-nav {
  display: flex;
}

.month-btn {
  padding: 5px 15px;
  cursor: pointer;
  border: 1px solid #ddd;
  background: none;
}

.month-btn.active {
  background-color: #2196f3;
  color: white;
}

.calendar-table {
  width: 100%;
}

.table-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  background-color: #e4edfa;

  font-weight: bold;
  text-align: center;
}

.table-body {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-auto-rows: minmax(80px, auto);
}

.table-row {
  display: contents;
}

.table-cell {
  padding: 10px;
  border: 1px solid #ddd;
  position: relative;
}

.date-number {
  font-weight: bold;
  margin-bottom: 15px;
}

.date-info {
  font-size: 12px;
}

.prod-total {
  margin-bottom: 10px;
  cursor: pointer;
}

.edit-link {
  color: #2196f3;
  cursor: pointer;
}

input[type="text"] {
  width: 80px;
  padding: 2px;
  font-size: 12px;
}
</style>
